import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import adminService from '../services/adminService';
import './FormStyles.css';

const AdminUserManagementPage = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedUser, setSelectedUser] = useState(null);
  const [showModal, setShowModal] = useState(false);
  const navigate = useNavigate();

  // 表单状态
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    phoneNumber: '',
    fullName: '',
    address: '',
    dateOfBirth: '',
  });

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      setLoading(true);
      const response = await adminService.getAllUsers();
      setUsers(response.data);
      setError(null);
    } catch (err) {
      setError('获取用户列表失败：' + (err.response?.data?.message || err.message));
      console.error('获取用户列表失败', err);
    } finally {
      setLoading(false);
    }
  };

  const handleEditUser = (user) => {
    setSelectedUser(user);
    setFormData({
      username: user.username,
      email: user.email,
      phoneNumber: user.phoneNumber || '',
      fullName: user.fullName || '',
      address: user.address || '',
      dateOfBirth: user.dateOfBirth || '',
    });
    setShowModal(true);
  };

  const handleDeleteUser = async (userId) => {
    if (window.confirm('确定要删除这个用户吗？此操作不可逆。')) {
      try {
        await adminService.deleteUser(userId);
        setUsers(users.filter(user => user.id !== userId));
        alert('用户删除成功');
      } catch (err) {
        alert('删除用户失败：' + (err.response?.data?.message || err.message));
        console.error('删除用户失败', err);
      }
    }
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value,
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await adminService.updateUser(selectedUser.id, formData);
      setUsers(users.map(user => user.id === selectedUser.id ? response.data : user));
      setShowModal(false);
      alert('用户信息更新成功');
    } catch (err) {
      alert('更新用户信息失败：' + (err.response?.data?.message || err.message));
      console.error('更新用户信息失败', err);
    }
  };

  if (loading) return <div className="loading">加载中...</div>;
  if (error) return <div className="error-message">{error}</div>;

  return (
    <div className="admin-container">
      <h1>用户管理</h1>
      
      <div className="user-list">
        <table>
          <thead>
            <tr>
              <th>用户名</th>
              <th>邮箱</th>
              <th>手机号</th>
              <th>姓名</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {users.map(user => (
              <tr key={user.id}>
                <td>{user.username}</td>
                <td>{user.email}</td>
                <td>{user.phoneNumber}</td>
                <td>{user.fullName}</td>
                <td>
                  <button onClick={() => handleEditUser(user)} className="btn btn-edit">编辑</button>
                  <button onClick={() => handleDeleteUser(user.id)} className="btn btn-delete">删除</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showModal && (
        <div className="modal">
          <div className="modal-content">
            <span className="close" onClick={() => setShowModal(false)}>&times;</span>
            <h2>编辑用户</h2>
            <form onSubmit={handleSubmit}>
              <div className="form-group">
                <label>用户名</label>
                <input 
                  type="text" 
                  name="username" 
                  value={formData.username} 
                  onChange={handleInputChange}
                  disabled
                />
              </div>
              <div className="form-group">
                <label>邮箱</label>
                <input 
                  type="email" 
                  name="email" 
                  value={formData.email} 
                  onChange={handleInputChange} 
                  required 
                />
              </div>
              <div className="form-group">
                <label>手机号</label>
                <input 
                  type="text" 
                  name="phoneNumber" 
                  value={formData.phoneNumber} 
                  onChange={handleInputChange} 
                />
              </div>
              <div className="form-group">
                <label>姓名</label>
                <input 
                  type="text" 
                  name="fullName" 
                  value={formData.fullName} 
                  onChange={handleInputChange} 
                />
              </div>
              <div className="form-group">
                <label>地址</label>
                <input 
                  type="text" 
                  name="address" 
                  value={formData.address} 
                  onChange={handleInputChange} 
                />
              </div>
              <div className="form-group">
                <label>出生日期</label>
                <input 
                  type="date" 
                  name="dateOfBirth" 
                  value={formData.dateOfBirth} 
                  onChange={handleInputChange} 
                />
              </div>
              <div className="form-group">
                <button type="submit" className="btn btn-primary">保存</button>
                <button type="button" onClick={() => setShowModal(false)} className="btn btn-secondary">取消</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default AdminUserManagementPage; 